Read the correlation ID from the incoming request header — set by upstream infrastructure or a middleware. Fall back to generating a new UUID if absent. Echo the ID back in both the response header and the response body so clients can correlate errors with distributed logs.
Upstream API gateways (AWS ALB, nginx) often inject x-correlation-id — always read it if present.
Fall back to randomUUID() so every error response has a trackable ID even without a gateway.
Set the ID in both the response header and body — some clients read headers, others parse the body.
Pair with a middleware that attaches the correlation ID to req at the start of every request lifecycle.
Log the correlation ID alongside every error so server logs and client error reports can be joined.